﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Material;
using SmartSiteManagementSystem.Models.DTO;
using System.Collections;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{

  
    public class MaterialController : AdminBaseControllers
    {

        private readonly ILogger<MaterialController> _logger;
        //注入后台服务
        private readonly IMaterialService _materialService;
        //注入后台服务
        private readonly IAdminService _adminService;
        public MaterialController(IAdminService adminService, IMaterialService materialService, ILogger<MaterialController> logger) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
            _materialService = materialService;
        }

        #region 分类相关页面

        /// <summary>
        /// 首页  
        /// </summary>
        public ViewResult CatalogIndex()
        {
            return View();
        }

        public ViewResult CatalogLeft()
        {
            return View();
        }
        /// <summary>
        /// 分类树
        /// </summary>
        /// <returns></returns>
        public JsonResult CatalogTree()
        {
            
            IList<MaterialCatalogInfo> gci = _materialService.GetMaterialCatalogInfoList(null);

            IEnumerable<MaterialCatalogInfo> rootGci = gci.Where(m => m.ParentId == 0).OrderBy<MaterialCatalogInfo, int>(
                Sgci => Sgci.SortOrder
                );

            List<TreeModel> tree = new List<TreeModel>();
            TreeModel node;
            foreach (var item in rootGci)
            {
                node = new TreeModel();
                node.id = item.CatalogId;
                node.text = item.CatalogName;
                node.children = GetTreeChild(gci, item);
                node.url = "CatalogEdit?operation=edit&parentId=0&catalogId=" + node.id;
                tree.Add(node);
            }
            //return Json(tree, JsonRequestBehavior.AllowGet);
            return Json(tree);
        }
        /// <summary>
        /// 获取子分类
        /// </summary>
        /// <param name="cataloglist"></param>
        /// <param name="curNode"></param>
        /// <returns></returns>
        private List<TreeModel> GetTreeChild(IList<MaterialCatalogInfo> cataloglist, MaterialCatalogInfo curNode)
        {
            IEnumerable<MaterialCatalogInfo> childlist = cataloglist.Where(m => m.ParentId == curNode.CatalogId).OrderBy<MaterialCatalogInfo, int>(
                Sgci => Sgci.SortOrder
                );
            List<TreeModel> tree = new List<TreeModel>();
            TreeModel node;
            foreach (MaterialCatalogInfo item in childlist)
            {
                node = new TreeModel();
                node.id = item.CatalogId;
                node.text = item.CatalogName;
                if (item.IsParent)
                {
                    node.children = GetTreeChild(cataloglist, item);
                }
                node.url = "CatalogEdit?operation=edit&parentId=" + curNode.ParentId + "&catalogId=" + node.id;
                tree.Add(node);
            }
            return tree;
        }

        /// <summary>
        /// 分类编辑
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ViewResult CatalogEdit(string operation, int catalogId, int parentId = 0)
        {
            operation = operation.ToLower();
            if (catalogId == 0)
            {
                operation = "add";
            }

            MaterialCatalogInfo parentCatalog = new MaterialCatalogInfo();
            MaterialCatalogInfo catalog = new MaterialCatalogInfo();
            if (operation == "add")
            {
                if (parentId > 0)
                {
                    parentCatalog = _materialService.GetMaterialCatalogInfoById(parentId);
                    catalog.ParentName = parentCatalog.CatalogName;
                    if ("一级分类".Equals(parentCatalog.SuperiorName))
                        catalog.SuperiorName = "二级分类";
                    if ("".Equals(parentCatalog.SuperiorName))
                        catalog.SuperiorName = "一级分类";
                }
                catalog.ParentId = parentId;
            }
            else if (operation == "edit")
            {
                catalog = _materialService.GetMaterialCatalogInfoById(catalogId);
                parentCatalog = _materialService.GetMaterialCatalogInfoById(catalog.ParentId);
                if (string.IsNullOrEmpty(catalog.SuperiorName) || "一级分类".Equals(catalog.SuperiorName))
                {
                    catalog.IsParent = true;
                }
            }

            ViewBag.Catalog = catalog;
            ViewBag.ParentCatalog = parentCatalog;
            ViewBag.CatalogId = catalogId;
            return View();
        }

        /// <summary>
        /// 分类编辑
        /// </summary>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <param name="sortOrder"></param>
        /// <param name="catalogName"></param>
        /// <param name="catalogLink"></param>
        /// <param name="countLadderJson"></param>
        /// <param name="keyWord"></param>
        /// <param name="stopFlog"></param>
        /// <param name="oldStopFlog"></param>
        /// <returns></returns>
        public JsonResult DoEditCatalog(int catalogId, int parentId, int sortOrder, string catalogName
            , int stopFlog = 0
            , int oldStopFlog = 0)
        {
            bool sf = stopFlog == 1;

            Hashtable param = new Hashtable();
            param.Add("sort_order", sortOrder);
            param.Add("parent_id", parentId);
            param.Add("is_stop", sf);
            param.Add("catalog_name", catalogName);
            param.Add("catalog_id", catalogId);
            int addId = 0;
            if (catalogId > 0)
            {
                if (sf && oldStopFlog == 0)
                {
                    string str = stopCatalog(catalogId);
                    if (!string.IsNullOrEmpty(str))
                    {
                        return Json(new { success = false, msg = str });
                    }
                }
                //启用该分类 判断父类是否处于停用状态
                if (!sf && oldStopFlog == 1)
                {
                    string msg = UnStopCatalog(catalogId);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        return Json(new { success = false, msg = msg });
                    }
                }
                //修改
                bool updateStatus = _materialService.UpdateMaterialCatalogInfo(param);
                if(updateStatus)
                {
                    addId = 1;
                }
                else
                {
                    addId = 0;
                }
                if (sf)
                {
                    SetSubCatalogStop(catalogId);
                }
                else
                {
                    string parentCatalogIds = _materialService.GetParentCatalogIds(catalogId);
                    if (!string.IsNullOrEmpty(parentCatalogIds))
                    {
                        string[] ParentCatalogIds = parentCatalogIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var parentCatalogId in ParentCatalogIds)
                        {
                            var parentCatalogObj = _materialService.GetMaterialCatalogInfoById(Int32.Parse(parentCatalogId));
                            if (!parentCatalogObj.IsStop)
                            {
                                continue;
                            }
                            parentCatalogObj.IsStop = false;
                            parentCatalogObj.UpdateTime = DateTime.Now;
                            _materialService.UpdateMaterialCatalogInfo(parentCatalogObj);
                        }
                    }
                }

                if (addId > 0)
                {
                    
                    return Json(new { success = true, msg = "修改成功!" });
                }
                else
                {
                    return Json(new { success = false, msg = "修改失败!" });
                }
            }
            else
            {
                MaterialCatalogInfo catalog = new MaterialCatalogInfo();
                catalog.SortOrder = sortOrder;
                catalog.ParentId = parentId;
                catalog.IsStop = sf;
                catalog.CatalogName = catalogName;
                catalog.CreateTime = DateTime.Now;
                catalog.UpdateTime = DateTime.Now;
                //新增
                addId = _materialService.InsertMaterialCatalogInfo(catalog);
                //如果添加的节点是某节点的子节点，则更新其父节点的IsParent字段为true
                if (addId > 0 && parentId > 0)
                {
                    MaterialCatalogInfo parentCatalog = _materialService.GetMaterialCatalogInfoById(parentId);
                    if (!parentCatalog.IsParent)
                    {
                        parentCatalog.IsParent = true;
                        parentCatalog.UpdateTime = DateTime.Now;
                        _materialService.UpdateMaterialCatalogInfo(parentCatalog);
                    }
                }

                if (addId > 0)
                {
                   
                    return Json(new { success = true, msg = "添加成功!" });
                }
                else
                {
                    return Json(new { success = false, msg = "添加失败!" });
                }
            }
        }

        /// <summary>
        /// 停用分类
        /// </summary>
        /// <param name="catalogId"></param>
        /// <returns></returns>
        private string stopCatalog(int catalogId)
        {
            var child = _materialService.GetChildListStopC(catalogId);
            if (child.Count > 0)
            {
                return "该分类下包含未停用的子分类，不允许停用！";
            }
            int _count = _materialService.GetMaterialInfoCountByCatalogId(catalogId);
            if (_count > 0)
            {
                return "该分类下面有物料，不允许停用！";
            }
            return null;
        }

        private string UnStopCatalog(int catalogId)
        {
            IList<MaterialCatalogInfo> infos = _materialService.GetParents(catalogId);
            string msg = "该分类父类处于停用状态，无法启用当前分类";
            foreach (MaterialCatalogInfo info in infos)
            {
                if (info.CatalogId == catalogId)
                    continue;
                if (info.IsStop)
                    return msg;
            }
            return null;
        }
        /// <summary>
        /// 设置所有子分类禁用或可用 (默认禁用)
        /// </summary>
        /// <param name="catalogId">分类Id</param>
        /// <param name="stopFlag">禁用标记</param>
        private void SetSubCatalogStop(int catalogId, bool stopFlag = true)
        {
            var catalogObjList = _materialService.GetCatalogChildList(catalogId);
            foreach (var catalogObj in catalogObjList)
            {
                if (!catalogObj.IsStop)
                {
                    catalogObj.IsStop = stopFlag;
                }
                SetSubCatalogStop(catalogObj.CatalogId);
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public JsonResult DoDeleteCatalog(int catalogId, int parentId = 0)
        {
            var child = _materialService.GetCatalogChildList(catalogId);
            if (child.Count > 0)
            {
                return Json(new { success = false, msg = "该分类下面有子分类，不允许删除！" });
            }
            else
            {
                int _count = _materialService.GetMaterialInfoCountByCatalogId(catalogId);
                if (_count > 0)
                {
                    return Json(new { success = false, msg = "该分类下面有物料，不允许删除！" });
                }
                else
                {
                    bool uResult = _materialService.DeleteMaterialCatalog(catalogId, parentId);

                    if (uResult)
                    {

                      
                        return Json(new { success = true, msg = "删除成功！" });
                    }
                    else
                    {
                       
                        return Json(new { success = false, msg = "删除失败！" });
                    }
                }
            }
        }

        /// <summary>
        /// 获取所有一级类别
        /// </summary>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetAllFirstCatalog()
        {
            Hashtable param = new Hashtable();
            param.Add("parent_id", 0);
            param.Add("is_stop", false);
            param.Add("is_deleted", false);
            IList<MaterialCatalogInfo> allFirstCatalog =_materialService.GetMaterialCatalogInfoList(param).ToList();
            MaterialCatalogInfo catalogInfo = new MaterialCatalogInfo();
            catalogInfo.CatalogId = 0;
            catalogInfo.CatalogName = "请选择";
            allFirstCatalog.Insert(0, catalogInfo);
            return Json(allFirstCatalog);
        }

        /// <summary>
        /// 通过父类别获取所有子类别
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetCatalogByParentId(int parentId)
        {
            //停用和禁用的都不显示
            IList<MaterialCatalogInfo> childCatalogs = new List<MaterialCatalogInfo>();
            if (parentId > 0)
            {
                childCatalogs = _materialService.GetCatalogChildList(parentId).Where(x => x.IsStop == false).ToList();
            }
            MaterialCatalogInfo catalogInfo = new MaterialCatalogInfo();
            catalogInfo.CatalogId = 0;
            catalogInfo.CatalogName = "请选择";
            childCatalogs.Insert(0, catalogInfo);
            return Json(childCatalogs);
        }

        /// <summary>
        /// 通过第三级类别Id获取数据
        /// </summary>
        /// <param name="thirdId"></param>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetCatalogByThirdId(int thirdId)
        {
            List<MaterialCatalogInfo> Catalogs = new List<MaterialCatalogInfo>();
            MaterialCatalogInfo catas1 = _materialService.GetMaterialCatalogInfoById(thirdId);
            if (catas1 == null || catas1.CatalogId == 0 || catas1.IsDeleted == true || catas1.IsStop == true)
            {

                return Json(Catalogs);
            }
            MaterialCatalogInfo catas2 = _materialService.GetMaterialCatalogInfoById(catas1.ParentId);

            if (catas2 == null || catas2.CatalogId == 0 || catas2.IsDeleted == true || catas2.IsStop == true)
            {
                return Json(Catalogs);
            }
            MaterialCatalogInfo catas3 = _materialService.GetMaterialCatalogInfoById(catas2.ParentId);
            if (catas3 == null || catas3.CatalogId == 0 || catas3.IsDeleted == true || catas3.IsStop == true)
            {
                return Json(Catalogs);
            }
            Catalogs.Add(catas3);
            Catalogs.Add(catas2);
            Catalogs.Add(catas1);
            return Json(Catalogs);
        }
        #endregion


        #region 物料相关页面
        /// <summary>
        ///  物料首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="catagoryId"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public void GetList(int catagoryId,string searchKey, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;

            Hashtable param = new Hashtable();
            param.Add("is_deleted", 0);//正常 0 false
            if (catagoryId>0)
                param.Add("catalog_id", catagoryId);
            int count =_materialService.GetMaterialInfoListCount(param);
            IList<MaterialInfo> list = _materialService.GetMaterialInfoList(param, "", page, rows);
            foreach(MaterialInfo item in list)
            {
                MaterialCatalogInfo catagory = _materialService.GetMaterialCatalogInfoById(item.CatalogId);
                if(catagory!=null)
                {
                    item.CatagoryName = catagory.CatalogName;
                }

            }
            var data = new
            {
                total = count,
                rows = list
            };

            HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(data));

        }


        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="materialId"></param>
        public void ajaxUpdateMaterialState(int materialId)
        {
            MaterialInfo materialInfo = null;
            bool success = false;
            if (materialId > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(materialId);
                materialInfo.IsStop = materialInfo.IsStop ? false : true;
                success = _materialService.UpdateMaterialInfo(materialInfo);

            }

            HttpContext.Response.WriteAsync(success.ToString());
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="materialId"></param>
        public void ajaxDeleteMaterial(int materialId)
        {
            bool success = false;
            if (materialId > 0)
            {
                MaterialInfo materialInfo = _materialService.GetMaterialInfoById(materialId);
                if (materialInfo != null)
                {
                    materialInfo.IsDeleted = true;
                    success = _materialService.UpdateMaterialInfo(materialInfo);
                }
            }
            HttpContext.Response.WriteAsync(success.ToString());
        }



        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Access(int id = 0)
        {
            MaterialInfo materialInfo = new MaterialInfo();
            if (id > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(id);
            }
            ViewBag.materialInfo = materialInfo;

            return View();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <param name="MaterialName"></param>
        /// <param name="CatalogId"></param>
        /// <param name="SingleWeight"></param>
        /// <param name="SortOrder"></param>
        /// <param name="Descript"></param>
        public void ajaxAccess(int MaterialId, string MaterialName, int CatalogId, string SingleWeight, int SortOrder, string Descript)
        {
            MaterialInfo materialInfo = null;
            bool success = false;
            int code = -1;
            if (MaterialId > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(MaterialId);
            }
            else
            {
                materialInfo = new MaterialInfo();
                materialInfo.IsStop = false;
            }
            materialInfo.IsDeleted = false;
            materialInfo.CatalogId = CatalogId;
            if(!string.IsNullOrEmpty(SingleWeight))
            {
                materialInfo.SingleWeight = decimal.Parse(SingleWeight);
            }

            materialInfo.SortOrder = SortOrder;
            materialInfo.Descript = Descript;
            materialInfo.MaterialName = MaterialName;

            if (MaterialId > 0)
            {
                success = _materialService.UpdateMaterialInfo(materialInfo);
                if (success)
                {
                    code = 1;
                }
            }
            else
            {
                MaterialId = _materialService.InsertMaterialInfo(materialInfo);
                success = MaterialId > 0 ? true : false;
                if (success)
                {
                    code = 1;
                }
            }
            HttpContext.Response.WriteAsync(code.ToString());
        }

        #endregion




    }
}
